package com.obor.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import com.google.gson.Gson;

/**
*
* @Company OBOR
* @Author 李志鹏
* @Description
* @Date 2019年4月29日
*
*/
@MappedTypes({Map.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MapTypeHandler extends BaseTypeHandler<Map<String,Object>> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Map<String, Object> parameter, JdbcType jdbcType)
			throws SQLException {
		// TODO Auto-generated method stub
		ps.setString(i, parameter.toString());
		
	}

	@Override
	public Map<String, Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {
		// TODO Auto-generated method stub
		
		
		String str = rs.getString(columnName);
		
		System.out.println(str);
		
		Map<String,Object> map = new HashMap<>();	
		
		if(StringUtils.isNoneBlank(str)) {
			Gson gson = new Gson();
			
			
			map = gson.fromJson(str, map.getClass());
			
			
		}
		
		return map;
	}

	@Override
	public Map<String, Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}
	
//	public static void main(String[] args) {
//		//String str = "{\"goods_id\":\"140861765\",\"cat_id\":\"210\"}";
//		
//		String str = "1:1";
//		Map<String,Object> map = new HashMap<>();
//		Gson gson = new Gson();
//		
//		map = gson.fromJson(str, map.getClass());
//		
//		System.out.println(map.toString());
//	}

}
